home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyc (Python 2.4)
-
- '''Implementation of interface declarations
-
- There are three flavors of declarations:
-
- - Declarations are used to simply name declared interfaces.
-
- - ImplementsDeclarations are used to express the interfaces that a
- class implements (that instances of the class provides).
-
- Implements specifications support inheriting interfaces.
-
- - ProvidesDeclarations are used to express interfaces directly
- provided by objects.
-
-
- $Id: declarations.py 27081 2004-08-12 19:56:31Z srichter $
- '''
- import sys
- import weakref
- from zope.interface.interface import InterfaceClass, Specification
- from ro import mergeOrderings, ro
- import exceptions
- from types import ClassType
- from zope.interface.advice import addClassAdvisor
- BuiltinImplementationSpecifications = { }
-
- class Declaration(Specification):
- '''Interface declarations
-
- '''
-
- def __init__(self, *interfaces):
- Specification.__init__(self, _normalizeargs(interfaces))
-
-
- def changed(self):
- Specification.changed(self)
-
- try:
- del self._v_attrs
- except AttributeError:
- pass
-
-
-
- def get():
- marker1 = object()
- marker2 = object()
-
- def get(self, name, default = None):
- """Query for an attribute description
-
- >>> import zope.interface
- >>> class I1(zope.interface.Interface):
- ... a11 = zope.interface.Attribute('a11')
- ... a12 = zope.interface.Attribute('a12')
- >>> class I2(zope.interface.Interface):
- ... a21 = zope.interface.Attribute('a21')
- ... a22 = zope.interface.Attribute('a22')
- ... a12 = zope.interface.Attribute('a212')
- >>> class I11(I1):
- ... a11 = zope.interface.Attribute('a111')
-
- >>> decl = Declaration(I11, I2)
- >>> decl.get('a11') is I11.get('a11')
- True
- >>> decl.get('a12') is I1.get('a12')
- True
- >>> decl.get('a21') is I2.get('a21')
- True
- >>> decl.get('a22') is I2.get('a22')
- True
- >>> decl.get('a')
- >>> decl.get('a', 42)
- 42
-
- We get None even with no interfaces:
-
- >>> decl = Declaration()
- >>> decl.get('a11')
- >>> decl.get('a11', 42)
- 42
-
- We get new data if e change interface bases:
-
- >>> decl.__bases__ = I11, I2
- >>> decl.get('a11') is I11.get('a11')
- True
- """
-
- try:
- attrs = self._v_attrs
- except AttributeError:
- attrs = self._v_attrs = { }
-
- attr = attrs.get(name, marker1)
- if attr is marker1:
- for iface in self:
- attr = iface.get(name, marker2)
- if attr is not marker2:
- break
- continue
- else:
- attr = marker2
- attrs[name] = attr
-
- if attr is marker2:
- return default
- else:
- return attr
-
- return get
-
- get = get()
-
- def __contains__(self, interface):
- '''Test whether an interface is in the specification
-
- for example::
-
- >>> from zope.interface import Interface
- >>> class I1(Interface): pass
- ...
- >>> class I2(I1): pass
- ...
- >>> class I3(Interface): pass
- ...
- >>> class I4(I3): pass
- ...
- >>> spec = Declaration(I2, I3)
- >>> spec = Declaration(I4, spec)
- >>> int(I1 in spec)
- 0
- >>> int(I2 in spec)
- 1
- >>> int(I3 in spec)
- 1
- >>> int(I4 in spec)
- 1
- '''
- if self.extends(interface):
- pass
- return interface in self.interfaces()
-
-
- def __iter__(self):
- """Return an iterator for the interfaces in the specification
-
- for example::
-
- >>> from zope.interface import Interface
- >>> class I1(Interface): pass
- ...
- >>> class I2(I1): pass
- ...
- >>> class I3(Interface): pass
- ...
- >>> class I4(I3): pass
- ...
- >>> spec = Declaration(I2, I3)
- >>> spec = Declaration(I4, spec)
- >>> i = iter(spec)
- >>> i.next().getName()
- 'I4'
- >>> i.next().getName()
- 'I2'
- >>> i.next().getName()
- 'I3'
- >>> list(i)
- []
- """
- return self.interfaces()
-
-
- def flattened(self):
- """Return an iterator of all included and extended interfaces
-
- for example::
-
- >>> from zope.interface import Interface
- >>> class I1(Interface): pass
- ...
- >>> class I2(I1): pass
- ...
- >>> class I3(Interface): pass
- ...
- >>> class I4(I3): pass
- ...
- >>> spec = Declaration(I2, I3)
- >>> spec = Declaration(I4, spec)
- >>> i = spec.flattened()
- >>> i.next().getName()
- 'I4'
- >>> i.next().getName()
- 'I2'
- >>> i.next().getName()
- 'I1'
- >>> i.next().getName()
- 'I3'
- >>> i.next().getName()
- 'Interface'
- >>> list(i)
- []
-
- """
- return iter(self.__iro__)
-
-
- def __sub__(self, other):
- """Remove interfaces from a specification
-
- Examples::
-
- >>> from zope.interface import Interface
- >>> class I1(Interface): pass
- ...
- >>> class I2(I1): pass
- ...
- >>> class I3(Interface): pass
- ...
- >>> class I4(I3): pass
- ...
- >>> spec = Declaration()
- >>> [iface.getName() for iface in spec]
- []
- >>> spec -= I1
- >>> [iface.getName() for iface in spec]
- []
- >>> spec -= Declaration(I1, I2)
- >>> [iface.getName() for iface in spec]
- []
- >>> spec = Declaration(I2, I4)
- >>> [iface.getName() for iface in spec]
- ['I2', 'I4']
- >>> [iface.getName() for iface in spec - I4]
- ['I2']
- >>> [iface.getName() for iface in spec - I1]
- ['I4']
- >>> [iface.getName() for iface
- ... in spec - Declaration(I3, I4)]
- ['I2']
-
- """
- return [](*_[1])
-
-
- def __add__(self, other):
- """Add two specifications or a specification and an interface
-
-
- Examples::
-
- >>> from zope.interface import Interface
- >>> class I1(Interface): pass
- ...
- >>> class I2(I1): pass
- ...
- >>> class I3(Interface): pass
- ...
- >>> class I4(I3): pass
- ...
- >>> spec = Declaration()
- >>> [iface.getName() for iface in spec]
- []
- >>> [iface.getName() for iface in spec+I1]
- ['I1']
- >>> [iface.getName() for iface in I1+spec]
- ['I1']
- >>> spec2 = spec
- >>> spec += I1
- >>> [iface.getName() for iface in spec]
- ['I1']
- >>> [iface.getName() for iface in spec2]
- []
- >>> spec2 += Declaration(I3, I4)
- >>> [iface.getName() for iface in spec2]
- ['I3', 'I4']
- >>> [iface.getName() for iface in spec+spec2]
- ['I1', 'I3', 'I4']
- >>> [iface.getName() for iface in spec2+spec]
- ['I3', 'I4', 'I1']
-
- """
- seen = { }
- result = []
- for i in self.interfaces():
- if i not in seen:
- seen[i] = 1
- result.append(i)
- continue
-
- for i in other.interfaces():
- if i not in seen:
- seen[i] = 1
- result.append(i)
- continue
-
- return Declaration(*result)
-
- __radd__ = __add__
-
- def __nonzero__(self):
- '''Test whether there are any interfaces in a specification.
-
- >>> from zope.interface import Interface
- >>> class I1(Interface): pass
- ...
- >>> spec = Declaration(I1)
- >>> int(bool(spec))
- 1
- >>> spec = Declaration()
- >>> int(bool(spec))
- 0
- '''
- return bool(self.__iro__)
-
-
-
- class Implements(Declaration):
- inherit = None
- declared = ()
- __name__ = '?'
-
- def __repr__(self):
- return '<implementedBy %s>' % self.__name__
-
-
-
- def implementedByFallback(cls):
- """Return the interfaces implemented for a class' instances
-
- The value returned is an IDeclaration.
-
- for example:
-
- >>> from zope.interface import Interface
- >>> class I1(Interface): pass
- ...
- >>> class I2(I1): pass
- ...
- >>> class I3(Interface): pass
- ...
- >>> class I4(I3): pass
- ...
- >>> class C1(object):
- ... implements(I2)
- >>> class C2(C1):
- ... implements(I3)
- >>> [i.getName() for i in implementedBy(C2)]
- ['I3', 'I2']
- """
-
- try:
- spec = cls.__dict__.get('__implemented__')
- except AttributeError:
- spec = getattr(cls, '__implemented__', None)
- if spec is None:
- spec = BuiltinImplementationSpecifications.get(cls)
- if spec is not None:
- return spec
-
- return _empty
-
- if spec.__class__ == Implements:
- return spec
-
- return Declaration(*_normalizeargs((spec,)))
-
- if isinstance(spec, Implements):
- return spec
-
- if spec is None:
- spec = BuiltinImplementationSpecifications.get(cls)
- if spec is not None:
- return spec
-
-
- spec.__name__ = getattr(cls, '__module__', '?') + '.' + cls.__name__
-
- try:
- cls.__implemented__ = spec
- if not hasattr(cls, '__providedBy__'):
- cls.__providedBy__ = objectSpecificationDescriptor
-
- if isinstance(cls, DescriptorAwareMetaClasses) and '__provides__' not in cls.__dict__:
- cls.__provides__ = ClassProvides(cls, getattr(cls, '__class__', type(cls)))
- except TypeError:
- Implements if spec is not None else []
- Implements if spec is not None else []
- if not isinstance(cls, type):
- raise TypeError('ImplementedBy called for non-type', cls)
-
- BuiltinImplementationSpecifications[cls] = spec
- except:
- Implements if spec is not None else []
-
- return spec
-
- implementedBy = implementedByFallback
-
- def classImplementsOnly(cls, *interfaces):
- """Declare the only interfaces implemented by instances of a class
-
- The arguments after the class are one or more interfaces or
- interface specifications (IDeclaration objects).
-
- The interfaces given (including the interfaces in the
- specifications) replace any previous declarations.
-
- Consider the following example::
-
- >>> from zope.interface import Interface
- >>> class I1(Interface): pass
- ...
- >>> class I2(Interface): pass
- ...
- >>> class I3(Interface): pass
- ...
- >>> class I4(Interface): pass
- ...
- >>> class A(object):
- ... implements(I3)
- >>> class B(object):
- ... implements(I4)
- >>> class C(A, B):
- ... pass
- >>> classImplementsOnly(C, I1, I2)
- >>> [i.getName() for i in implementedBy(C)]
- ['I1', 'I2']
-
- Instances of ``C`` provide only ``I1``, ``I2``, and regardless of
- whatever interfaces instances of ``A`` and ``B`` implement.
-
- """
- spec = implementedBy(cls)
- spec.__bases__ = tuple(_normalizeargs(interfaces))
- spec.inherit = None
-
-
- def classImplements(cls, *interfaces):
- """Declare additional interfaces implemented for instances of a class
-
- The arguments after the class are one or more interfaces or
- interface specifications (IDeclaration objects).
-
- The interfaces given (including the interfaces in the
- specifications) are added to any interfaces previously
- declared.
-
- Consider the following example::
-
-
- for example:
-
- >>> from zope.interface import Interface
- >>> class I1(Interface): pass
- ...
- >>> class I2(Interface): pass
- ...
- >>> class I3(Interface): pass
- ...
- >>> class I4(Interface): pass
- ...
- >>> class I5(Interface): pass
- ...
- >>> class A(object):
- ... implements(I3)
- >>> class B(object):
- ... implements(I4)
- >>> class C(A, B):
- ... pass
- >>> classImplements(C, I1, I2)
- >>> [i.getName() for i in implementedBy(C)]
- ['I1', 'I2', 'I3', 'I4']
- >>> classImplements(C, I5)
- >>> [i.getName() for i in implementedBy(C)]
- ['I1', 'I2', 'I5', 'I3', 'I4']
-
- Instances of ``C`` provide ``I1``, ``I2``, ``I5``, and whatever
- interfaces instances of ``A`` and ``B`` provide.
-
- """
- spec = implementedBy(cls)
- spec.declared += tuple(_normalizeargs(interfaces))
- bases = []
- seen = { }
- for b in spec.declared:
- if b not in seen:
- seen[b] = 1
- bases.append(b)
- continue
- spec
-
- if spec.inherit is not None:
- for c in spec.inherit.__bases__:
- b = implementedBy(c)
- if b not in seen:
- seen[b] = 1
- bases.append(b)
- continue
-
-
- spec.__bases__ = tuple(bases)
-
-
- def _implements_advice(cls):
- (interfaces, classImplements) = cls.__dict__['__implements_advice_data__']
- del cls.__implements_advice_data__
- classImplements(cls, *interfaces)
- return cls
-
-
- def _implements(name, interfaces, classImplements):
- frame = sys._getframe(2)
- locals = frame.f_locals
- if locals is frame.f_globals or '__module__' not in locals:
- raise TypeError(name + ' can be used only from a class definition.')
-
- if '__implements_advice_data__' in locals:
- raise TypeError(name + ' can be used only once in a class definition.')
-
- locals['__implements_advice_data__'] = (interfaces, classImplements)
- addClassAdvisor(_implements_advice, depth = 3)
-
-
- def implements(*interfaces):
- '''Declare interfaces implemented by instances of a class
-
- This function is called in a class definition.
-
- The arguments are one or more interfaces or interface
- specifications (IDeclaration objects).
-
- The interfaces given (including the interfaces in the
- specifications) are added to any interfaces previously
- declared.
-
- Previous declarations include declarations for base classes
- unless implementsOnly was used.
-
- This function is provided for convenience. It provides a more
- convenient way to call classImplements. For example::
-
- implements(I1)
-
- is equivalent to calling::
-
- classImplements(C, I1)
-
- after the class has been created.
-
- Consider the following example::
-
-
- >>> from zope.interface import Interface
- >>> class IA1(Interface): pass
- ...
- >>> class IA2(Interface): pass
- ...
- >>> class IB(Interface): pass
- ...
- >>> class IC(Interface): pass
- ...
- >>> class A(object): implements(IA1, IA2)
- ...
- >>> class B(object): implements(IB)
- ...
-
- >>> class C(A, B):
- ... implements(IC)
-
- >>> ob = C()
- >>> int(IA1 in providedBy(ob))
- 1
- >>> int(IA2 in providedBy(ob))
- 1
- >>> int(IB in providedBy(ob))
- 1
- >>> int(IC in providedBy(ob))
- 1
-
- Instances of ``C`` implement ``I1``, ``I2``, and whatever interfaces
- instances of ``A`` and ``B`` implement.
-
- '''
- _implements('implements', interfaces, classImplements)
-
-
- def implementsOnly(*interfaces):
- '''Declare the only interfaces implemented by instances of a class
-
- This function is called in a class definition.
-
- The arguments are one or more interfaces or interface
- specifications (IDeclaration objects).
-
- Previous declarations including declarations for base classes
- are overridden.
-
- This function is provided for convenience. It provides a more
- convenient way to call classImplementsOnly. For example::
-
- implementsOnly(I1)
-
- is equivalent to calling::
-
- classImplementsOnly(I1)
-
- after the class has been created.
-
- Consider the following example::
-
- >>> from zope.interface import Interface
- >>> class IA1(Interface): pass
- ...
- >>> class IA2(Interface): pass
- ...
- >>> class IB(Interface): pass
- ...
- >>> class IC(Interface): pass
- ...
- >>> class A(object): implements(IA1, IA2)
- ...
- >>> class B(object): implements(IB)
- ...
-
- >>> class C(A, B):
- ... implementsOnly(IC)
-
- >>> ob = C()
- >>> int(IA1 in providedBy(ob))
- 0
- >>> int(IA2 in providedBy(ob))
- 0
- >>> int(IB in providedBy(ob))
- 0
- >>> int(IC in providedBy(ob))
- 1
-
-
- Instances of ``C`` implement ``IC``, regardless of what
- instances of ``A`` and ``B`` implement.
-
- '''
- _implements('implementsOnly', interfaces, classImplementsOnly)
-
-
- class Provides(Declaration):
- '''Implement __provides__, the instance-specific specification
-
- When an object is pickled, we pickle the interfaces that it implements.
- '''
-
- def __init__(self, cls, *interfaces):
- self._Provides__args = (cls,) + interfaces
- self._cls = cls
- Declaration.__init__(self, *interfaces + (implementedBy(cls),))
-
-
- def __reduce__(self):
- return (Provides, self._Provides__args)
-
- __module__ = 'zope.interface'
-
- def __get__(self, inst, cls):
- """Make sure that a class __provides__ doesn't leak to an instance
-
- For example::
-
- >>> from zope.interface import Interface
- >>> class IFooFactory(Interface): pass
- ...
-
- >>> class C(object):
- ... pass
-
- >>> C.__provides__ = ProvidesClass(C, IFooFactory)
- >>> [i.getName() for i in C.__provides__]
- ['IFooFactory']
- >>> getattr(C(), '__provides__', 0)
- 0
-
- """
- if inst is None and cls is self._cls:
- return self
-
- raise AttributeError, '__provides__'
-
-
- ProvidesClass = Provides
- InstanceDeclarations = weakref.WeakValueDictionary()
-
- def Provides(*interfaces):
- '''Cache instance declarations
-
- Instance declarations are shared among instances that have the
- same declaration. The declarations are cached in an weak value
- dictionary.
-
- (Note that, in the examples below, we are going to make
- assertions about the size of the weakvalue dictionary. For the
- assertions to be meaningful, we need to force garbage
- collection to make sure garbage objects are, indeed, removed
- from the system. Depending on how Python is run, we may need to
- make multiple calls to be sure. We provide a collect function
- to help with this:
-
- >>> import gc
- >>> def collect():
- ... for i in range(4):
- ... gc.collect()
-
- )
-
- >>> collect()
- >>> before = len(InstanceDeclarations)
-
- >>> class C(object):
- ... pass
-
- >>> from zope.interface import Interface
- >>> class I(Interface):
- ... pass
-
- >>> c1 = C()
- >>> c2 = C()
-
- >>> len(InstanceDeclarations) == before
- 1
-
- >>> directlyProvides(c1, I)
- >>> len(InstanceDeclarations) == before + 1
- 1
-
- >>> directlyProvides(c2, I)
- >>> len(InstanceDeclarations) == before + 1
- 1
-
- >>> del c1
- >>> collect()
- >>> len(InstanceDeclarations) == before + 1
- 1
-
- >>> del c2
- >>> collect()
- >>> len(InstanceDeclarations) == before
- 1
-
- '''
- spec = InstanceDeclarations.get(interfaces)
- if spec is None:
- spec = ProvidesClass(*interfaces)
- InstanceDeclarations[interfaces] = spec
-
- return spec
-
- Provides.__safe_for_unpickling__ = True
- DescriptorAwareMetaClasses = (ClassType, type)
-
- def directlyProvides(object, *interfaces):
- """Declare interfaces declared directly for an object
-
- The arguments after the object are one or more interfaces or
- interface specifications (IDeclaration objects).
-
- The interfaces given (including the interfaces in the
- specifications) replace interfaces previously
- declared for the object.
-
- Consider the following example::
-
- >>> from zope.interface import Interface
- >>> class I1(Interface): pass
- ...
- >>> class I2(Interface): pass
- ...
- >>> class IA1(Interface): pass
- ...
- >>> class IA2(Interface): pass
- ...
- >>> class IB(Interface): pass
- ...
- >>> class IC(Interface): pass
- ...
- >>> class A(object): implements(IA1, IA2)
- ...
- >>> class B(object): implements(IB)
- ...
-
- >>> class C(A, B):
- ... implements(IC)
-
- >>> ob = C()
- >>> directlyProvides(ob, I1, I2)
- >>> int(I1 in providedBy(ob))
- 1
- >>> int(I2 in providedBy(ob))
- 1
- >>> int(IA1 in providedBy(ob))
- 1
- >>> int(IA2 in providedBy(ob))
- 1
- >>> int(IB in providedBy(ob))
- 1
- >>> int(IC in providedBy(ob))
- 1
-
- The object, ``ob`` provides ``I1``, ``I2``, and whatever interfaces
- instances have been declared for instances of ``C``.
-
- To remove directly provided interfaces, use ``directlyProvidedBy`` and
- subtract the unwanted interfaces. For example::
-
- >>> directlyProvides(ob, directlyProvidedBy(ob)-I2)
- >>> int(I1 in providedBy(ob))
- 1
- >>> int(I2 in providedBy(ob))
- 0
-
- removes I2 from the interfaces directly provided by
- ``ob``. The object, ``ob`` no longer directly provides ``I2``,
- although it might still provide ``I2`` if it's class
- implements ``I2``.
-
- To add directly provided interfaces, use ``directlyProvidedBy`` and
- include additional interfaces. For example::
-
- >>> int(I2 in providedBy(ob))
- 0
- >>> directlyProvides(ob, directlyProvidedBy(ob), I2)
-
- adds I2 to the interfaces directly provided by ob::
-
- >>> int(I2 in providedBy(ob))
- 1
-
- """
- cls = getattr(object, '__class__', None)
- if cls is not None and getattr(cls, '__class__', None) is cls:
- if not isinstance(object, DescriptorAwareMetaClasses):
- raise TypeError('Attempt to make an interface declaration on a non-descriptor-aware class')
-
-
- interfaces = _normalizeargs(interfaces)
- if cls is None:
- cls = type(object)
-
- issub = False
- for damc in DescriptorAwareMetaClasses:
- if issubclass(cls, damc):
- issub = True
- break
- continue
-
- if issub:
- object.__provides__ = ClassProvides(object, cls, *interfaces)
- else:
- object.__provides__ = Provides(cls, *interfaces)
-
-
- class ClassProvidesBasePy(object):
-
- def __get__(self, inst, cls):
- if cls is self._cls:
- if inst is None:
- return self
-
- return self._implements
-
- raise AttributeError, '__provides__'
-
-
- ClassProvidesBase = ClassProvidesBasePy
-
- try:
- import _zope_interface_coptimizations
- except ImportError:
- pass
-
- from _zope_interface_coptimizations import ClassProvidesBase
-
- class ClassProvides(Declaration, ClassProvidesBase):
- """Special descriptor for class __provides__
-
- The descriptor caches the implementedBy info, so that
- we can get declarations for objects without instance-specific
- interfaces a bit quicker.
-
- For example::
-
- >>> from zope.interface import Interface
- >>> class IFooFactory(Interface):
- ... pass
- >>> class IFoo(Interface):
- ... pass
- >>> class C(object):
- ... implements(IFoo)
- ... classProvides(IFooFactory)
- >>> [i.getName() for i in C.__provides__]
- ['IFooFactory']
-
- >>> [i.getName() for i in C().__provides__]
- ['IFoo']
-
-
- """
-
- def __init__(self, cls, metacls, *interfaces):
- self._cls = cls
- self._implements = implementedBy(cls)
- self._ClassProvides__args = (cls, metacls) + interfaces
- Declaration.__init__(self, *interfaces + (implementedBy(metacls),))
-
-
- def __reduce__(self):
- return (self.__class__, self._ClassProvides__args)
-
- __get__ = ClassProvidesBase.__get__
-
-
- def directlyProvidedBy(object):
- '''Return the interfaces directly provided by the given object
-
- The value returned is an IDeclaration.
-
- '''
- provides = getattr(object, '__provides__', None)
- if provides is None or isinstance(provides, Implements):
- return _empty
-
- return Declaration(provides.__bases__[:-1])
-
-
- def classProvides(*interfaces):
- """Declare interfaces provided directly by a class
-
- This function is called in a class definition.
-
- The arguments are one or more interfaces or interface
- specifications (IDeclaration objects).
-
- The given interfaces (including the interfaces in the
- specifications) are used to create the class's direct-object
- interface specification. An error will be raised if the module
- class has an direct interface specification. In other words, it is
- an error to call this function more than once in a class
- definition.
-
- Note that the given interfaces have nothing to do with the
- interfaces implemented by instances of the class.
-
- This function is provided for convenience. It provides a more
- convenient way to call directlyProvidedByProvides for a class. For
- example::
-
- classProvides(I1)
-
- is equivalent to calling::
-
- directlyProvides(theclass, I1)
-
- after the class has been created.
-
- For example::
-
- >>> from zope.interface import Interface
- >>> class IFoo(Interface): pass
- ...
- >>> class IFooFactory(Interface): pass
- ...
- >>> class C(object):
- ... implements(IFoo)
- ... classProvides(IFooFactory)
- >>> [i.getName() for i in C.__providedBy__]
- ['IFooFactory']
- >>> [i.getName() for i in C().__providedBy__]
- ['IFoo']
-
- if equivalent to::
-
- >>> from zope.interface import Interface
- >>> class IFoo(Interface): pass
- ...
- >>> class IFooFactory(Interface): pass
- ...
- >>> class C(object):
- ... implements(IFoo)
- >>> directlyProvides(C, IFooFactory)
- >>> [i.getName() for i in C.__providedBy__]
- ['IFooFactory']
- >>> [i.getName() for i in C().__providedBy__]
- ['IFoo']
-
-
- """
- frame = sys._getframe(1)
- locals = frame.f_locals
- if locals is frame.f_globals or '__module__' not in locals:
- raise TypeError(name + ' can be used only from a class definition.')
-
- if '__provides__' in locals:
- raise TypeError('classProvides can only be used once in a class definition.')
-
- locals['__provides__'] = _normalizeargs(interfaces)
- addClassAdvisor(_classProvides_advice, depth = 2)
-
-
- def _classProvides_advice(cls):
- interfaces = cls.__dict__['__provides__']
- del cls.__provides__
- directlyProvides(cls, *interfaces)
- return cls
-
-
- def moduleProvides(*interfaces):
- """Declare interfaces provided by a module
-
- This function is used in a module definition.
-
- The arguments are one or more interfaces or interface
- specifications (IDeclaration objects).
-
- The given interfaces (including the interfaces in the
- specifications) are used to create the module's direct-object
- interface specification. An error will be raised if the module
- already has an interface specification. In other words, it is
- an error to call this function more than once in a module
- definition.
-
- This function is provided for convenience. It provides a more
- convenient way to call directlyProvides. For example::
-
- moduleImplements(I1)
-
- is equivalent to::
-
- directlyProvides(sys.modules[__name__], I1)
-
- """
- frame = sys._getframe(1)
- locals = frame.f_locals
- if locals is not frame.f_globals or '__name__' not in locals:
- raise TypeError('moduleProvides can only be used from a module definition.')
-
- if '__provides__' in locals:
- raise TypeError('moduleProvides can only be used once in a module definition.')
-
- module = sys.modules[__name__]
- locals['__provides__'] = Provides(type(module), *_normalizeargs(interfaces))
-
-
- def ObjectSpecification(direct, cls):
- """Provide object specifications
-
- These combine information for the object and for it's classes.
-
- For example::
-
- >>> from zope.interface import Interface
- >>> class I1(Interface): pass
- ...
- >>> class I2(Interface): pass
- ...
- >>> class I3(Interface): pass
- ...
- >>> class I31(I3): pass
- ...
- >>> class I4(Interface): pass
- ...
- >>> class I5(Interface): pass
- ...
- >>> class A(object): implements(I1)
- ...
- >>> class B(object): __implemented__ = I2
- ...
- >>> class C(A, B): implements(I31)
- ...
- >>> c = C()
- >>> directlyProvides(c, I4)
- >>> [i.getName() for i in providedBy(c)]
- ['I4', 'I31', 'I1', 'I2']
- >>> [i.getName() for i in providedBy(c).flattened()]
- ['I4', 'I31', 'I3', 'I1', 'I2', 'Interface']
- >>> int(I1 in providedBy(c))
- 1
- >>> int(I3 in providedBy(c))
- 0
- >>> int(providedBy(c).extends(I3))
- 1
- >>> int(providedBy(c).extends(I31))
- 1
- >>> int(providedBy(c).extends(I5))
- 0
- >>> class COnly(A, B): implementsOnly(I31)
- ...
- >>> class D(COnly): implements(I5)
- ...
- >>> c = D()
- >>> directlyProvides(c, I4)
- >>> [i.getName() for i in providedBy(c)]
- ['I4', 'I5', 'I31']
- >>> [i.getName() for i in providedBy(c).flattened()]
- ['I4', 'I5', 'I31', 'I3', 'Interface']
- >>> int(I1 in providedBy(c))
- 0
- >>> int(I3 in providedBy(c))
- 0
- >>> int(providedBy(c).extends(I3))
- 1
- >>> int(providedBy(c).extends(I1))
- 0
- >>> int(providedBy(c).extends(I31))
- 1
- >>> int(providedBy(c).extends(I5))
- 1
-
-
- nonzero:
-
- >>> from zope.interface import Interface
- >>> class I1(Interface):
- ... pass
- >>> class I2(Interface):
- ... pass
- >>> class C(object):
- ... implements(I1)
- >>> c = C()
- >>> int(bool(providedBy(c)))
- 1
- >>> directlyProvides(c, I2)
- >>> int(bool(providedBy(c)))
- 1
- >>> class C(object):
- ... pass
- >>> c = C()
- >>> int(bool(providedBy(c)))
- 0
- >>> directlyProvides(c, I2)
- >>> int(bool(providedBy(c)))
- 1
-
-
- """
- return Provides(cls, direct)
-
-
- def getObjectSpecification(ob):
- provides = getattr(ob, '__provides__', None)
- if provides is not None:
- return provides
-
-
- try:
- cls = ob.__class__
- except AttributeError:
- return _empty
-
- return implementedBy(cls)
-
-
- def providedBy(ob):
-
- try:
- r = ob.__providedBy__
- except AttributeError:
- return getObjectSpecification(ob)
-
-
- try:
- r.extends
- except AttributeError:
-
- try:
- r = ob.__provides__
- except AttributeError:
- return implementedBy(ob.__class__)
-
-
- try:
- cp = ob.__class__.__provides__
- except AttributeError:
- return r
-
- if r is cp:
- return implementedBy(ob.__class__)
-
- except:
- r is cp
-
- return r
-
-
- class ObjectSpecificationDescriptorPy(object):
- '''Implement the __providedBy__ attribute
-
- The __providedBy__ attribute computes the interfaces peovided by
- an object.
- '''
-
- def __get__(self, inst, cls):
- """Get an object specification for an object
-
- For example::
-
- >>> from zope.interface import Interface
- >>> class IFoo(Interface): pass
- ...
- >>> class IFooFactory(Interface): pass
- ...
- >>> class C(object):
- ... implements(IFoo)
- ... classProvides(IFooFactory)
- >>> [i.getName() for i in C.__providedBy__]
- ['IFooFactory']
- >>> [i.getName() for i in C().__providedBy__]
- ['IFoo']
-
- """
- if inst is None:
- return getObjectSpecification(cls)
-
- provides = getattr(inst, '__provides__', None)
- if provides is not None:
- return provides
-
- return implementedBy(cls)
-
-
- ObjectSpecificationDescriptor = ObjectSpecificationDescriptorPy
-
- def _normalizeargs(sequence, output = None):
- '''Normalize declaration arguments
-
- Normalization arguments might contain Declarions, tuples, or single
- interfaces.
-
- Anything but individial interfaces or implements specs will be expanded.
- '''
- if output is None:
- output = []
-
- cls = sequence.__class__
- if InterfaceClass in cls.__mro__ or Implements in cls.__mro__:
- output.append(sequence)
- else:
- for v in sequence:
- _normalizeargs(v, output)
-
- return output
-
- _empty = Declaration()
-
- try:
- import _zope_interface_coptimizations
- except ImportError:
- pass
-
- from _zope_interface_coptimizations import implementedBy, providedBy
- from _zope_interface_coptimizations import getObjectSpecification
- from _zope_interface_coptimizations import ObjectSpecificationDescriptor
- objectSpecificationDescriptor = ObjectSpecificationDescriptor()
-